﻿using System;
using System.Security.Principal;
using System.Threading;
using System.Web;
using MCP.BL;
using MCP.BL.Messages;
using MCP.Model.Repositories.Interfaces;
using client = MCP.Data.Client;
using server = MCP.Data.CF_Entities;
using MCP.Model.Repositories;

namespace MCP.Model.Helpers
{
	public static class CurrentUserHelper
	{
		public static int UserID { get { return HttpContext.Current.GetUser().UserID; } }

		public static string Username { get { return Thread.CurrentPrincipal.Identity.Name; } }

		public static client.CurrentUser User { get { return HttpContext.Current.GetUser(); } }

		/// <summary>
		/// Sets CurrentUser in Session.
		/// </summary>
		/// <param name="username">Authorized user username.</param>
		/// <param name="role">Authorized user role.</param>
		/// <param name="unitOfWork">DB managment.</param>
		/// <returns>False if no corresponding user was found in DB.</returns>
		public static OperationResult SetCurrentUser(string username, string role, IUnitOfWork unitOfWork)
		{
		    OperationResult result;

			try
			{
				var getUserResult = unitOfWork.AccountRepository.GetUser(username);
                if (getUserResult.Success)
                {
                    var currentUser = getUserResult.Result.ToCurrentUser(getUserResult.Result.Settings);

					Thread.CurrentPrincipal = new GenericPrincipal(new GenericIdentity(username), new string[] { role });
					HttpContext.Current.Session["CurrentUser"] = currentUser;

				    result = new OperationResult(true);
				}
				else
				{
				    result = new OperationResult(false, new ErrorMessage("Unable to find user with such username."));
				}
			}
			catch (Exception exc)
			{
				result = new OperationResult(exc);
			}

			
			return result;
		}

        public static OperationResult UpdateCurrentUserSettings(UnitOfWork unitOfWork)
        {
            OperationResult result;

            try
            {
                var settings = unitOfWork.SettingsRepository.GetSettings_Client();
                
                // update reference:
                var currentUser = HttpContext.Current.Session["CurrentUser"] as client.CurrentUser;
                if (currentUser != null)
                {
                    currentUser.FirstName = settings.FirstName;
                    currentUser.LastName = settings.LastName;
                    currentUser.MonthIncome = settings.MonthIncome;
                    currentUser.MinBalance = settings.MinBalance;
                }

                result = new OperationResult(true);
            }
            catch (Exception exception)
            {
                result = new OperationResult(exception);
            }

            return result;
        }
	}
}